#!/bin/sh

####---------------------------------------------------------####
# daemonize command shell
#
PID_prefix='...'
LOG_out='...'
LOG_err='...'

STATUS_OK=0
STATUS_FAIL=1
STATUS_UNKNOWN=2
waitup()
{
    PID=$1
    TEST_TIMES=3
    COUNT_SUCCESS=0
    i=0
    while [ $i -lt $TEST_TIMES ]
    do
        OK=`ps $PID`
        if [ $? -eq 0 ]; then
            COUNT_SUCCESS=`expr $COUNT_SUCCESS + 1`
        fi
        i=`expr $i + 1`
        sleep 1
    done

    if [ $COUNT_SUCCESS -eq 0 ]; then
        # FAILURE
        return $STATUS_FAIL
    fi
    if [ $TEST_TIMES -eq $COUNT_SUCCESS ]; then
        # SUCCESS
        return $STATUS_OK
    fi
    # UNSTEADY
    return  $STATUS_UNKNOWN
}

${CMD_} ${CONFIG_}  1>>"${LOG_out}" 2>>"${LOG_err}" &
PID=$!
STATUS=$STATUS_UNKNOWN
while [ $STATUS -eq $STATUS_UNKNOWN ]
do
    waitup $PID
    STATUS=$?
    if [ $STATUS -eq $STATUS_OK ]; then
        echo "${APPROOT}/bin/start" >"${PID_prefix}.${PID}.pid"
        break
    fi
    if [ $STATUS -eq $STATUS_FAIL ]; then
        exit 1
    fi
done

####---------------------------------------------------------------------------------####
# down the process
PID_files="${PID_prefix}.*.pid"

COUNT=`ls $PID_files 2>/dev/null | wc -l | awk '{print $1}'`
while [ $COUNT -gt 0 ]
do
    for file in `ls $PID_files 2>/dev/null`
    do
        PID=`echo $file | awk -F'.' '{print $2}'`
        kill $PID 2>/dev/null
        #kill -0 $PID 2>/dev/null
        DUMMY=`ps $PID`
        if [ $? -ne 0 ]
        then
            # PID NOT exists, or permission denied
            rm $file
        fi
    done

    COUNT=`ls $PID_files 2>/dev/null | wc -l | awk '{print $1}'`
    if [ $COUNT -gt 0 ]
    then
        sleep 1
    fi
done

####---------------------------------------------------------------------------####
makePidFile()
{
    PID=$1
    CMDLINE=$2
    PIDFILE=$3

    STATUS=$STATUS_UNKNOWN


    while [ $STATUS -eq $STATUS_UNKNOWN ]
    do 
        waitup $PID
        STATUS=$?
        if [ $STATUS -eq $STATUS_OK ]; then
            echo "${CMDLINE}" >"${PIDFILE}"
            echo "daemonizing ..."
            break
        fi
        if [ $STATUS -eq $STATUS_FAIL ]; then
            exit 1
        fi
    done
}


